<?php

namespace Modules\Edu\Http\Controllers\Admin;

use App\Services\WeChatService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Modules\Edu\Entities\System;
use Modules\Edu\Http\Requests\SystemLessonRequest;
use Illuminate\Support\Facades\Log;

class SystemController extends Controller
{

    public function index()
    {
        $systems = System::all();
        return view('edu::system.index', compact('systems'));
    }

    public function create(System $system)
    {

        return view('edu::system.create', compact('system'));
    }

    public function store(SystemLessonRequest $request, System $system, WeChatService $weChatService)
    {

        $this->fillData($request, $system);

        $this->saveWechatRule($system);

        return redirect()->route('edu.admin.system.index')->with('success', '课程添加成功');
    }

    public function saveWechatRule($system)
    {

        $weChatService = app(WeChatService::class);
        $rule = $weChatService->save(
            null,
            module()['name'], [
                'type' => 'system',
                'id' => $system['id']
            ]
        );
        if ($rule) {
            $system->rule_id = $rule['id'];
            $system->save();
        }

    }

    public function edit(System $system)
    {
        $this->authorize('edit', $system);
        return view('edu::system.edit', compact('system'));
    }


    public function update(SystemLessonRequest $request, System $system)
    {
        //
        $this->fillData($request, $system);

        $this->saveWechatRule($system);

        return redirect()->route('edu.admin.system.index')->with('success', '课程编辑成功');

    }

    public function destroy(System $system)
    {
        //
        $system->delete();
        return response()->json(['message', '删除成功']);

    }

    protected function updateLessons(Request $request, System $system)
    {

        $lessons = array_map(function ($v) {
            return $v['id'];
        }, json_decode($request->input('lessons', ''), true));


        if (!empty($lessons)) {
            $system->lessons()->detach();
            foreach ($lessons as $rank => $id) {
                $system->lessons()->attach($id, ['rank' => $rank]);
            }
        }

    }

    protected function fillData($request, $system)
    {
        $system->fill($request->input());
        $system->site_id = site()['id'];
        $system->user_id = user('id');
        $system->save();
        $this->updateLessons($request, $system);
    }
}
